<template>
  <div>
    <Header></Header>
    <div class="mt-5">
      <img :src="img" alt="" class="d-block img-book">
    </div>
    <div class="white">
      <form enctype="multipart/form-data">
        <a><label for="file">更换头像</label></a>
        <input type="file" id="file" name="file" @change="filesChangeToBase64($event.target.name, $event.target.files)"
          accept="image/*" style="display: none;">
      </form>
    </div>
    <!-- <form enctype="multipart/form-data" novalidate>
      <h1>上传图片</h1>
      <div class="dropbox">
        <input type="file" multiple :name="uploadFieldName" :disabled="isSaving"
          @change="filesChange($event.target.name, $event.target.files);fileCount = $event.target.files.length"
          accept="image/*" class="input-file">
        <p v-if="isInitial"> 拖拽您的文件到这里开始<br> 或者点击浏览 </p>
        <p v-if="isSaving"> 正在上传 { { fileCount }} 个文件... </p>
      </div>
    </form> -->
  </div>
</template>

<script>
import Header from './components/Header.vue'
export default {
  components: {
    Header
  },
  data() {
    return {
      img: this.$store.state.imgbase64,
      avatarid: this.$store.state.avatarid
    }
  },

  methods: {
    filesChange(fieldName, fileList) {
      const formData = new FormData()
      if (!fileList.length) return
      Array.from(Array(fileList.length).keys())
        .map(x => {
          formData.append(fieldName, fileList[x], fileList[x].name)
        })
      formData.append('token', this.$store.state.token)
      this.post('uploadBinary', formData).then((res) => {
        this.alert(res.data.msg, { type: 'success', placement: 'top' })
      })
    },
    filesChangeToBase64(fieldName, fileList) {
      if (!fileList.length) return
      let _this = this
      Array.from(Array(fileList.length).keys())
        .map(x => {
          var file = fileList[x]
          // 创建文件读取器，设置读取为 base64 编码
          var reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = function () {
            let base64 = reader.result
            _this.post('uploadBase64', {
              file: base64
            }).then((res) => {
              _this.$store.state.imgbase64 = base64
              _this.img = base64
              _this.alert(res.data.msg, { type: 'success', placement: 'top' })
            })
          }
        })
    }
  }
}
</script>

<style lang='scss' scoped>
a {
  margin: 0 auto;
  height: 2rem;
  line-height: 2rem;
  margin-bottom: 0.5rem;
  display: flex;
  justify-content: center;
}

.white {
  border-radius: .25rem;
}
</style>
